package com.krtech.wecard.module.weixin.handler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.krtech.wecard.module.sys.entity.SysUser;
import com.krtech.wecard.module.sys.service.LoginService;
import com.krtech.wecard.module.sys.service.SysUserService;
import com.krtech.wecard.module.weixin.bean.WxOpenIdManage;
import com.krtech.wecard.module.weixin.service.WxOpenIdManageService;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@Component
public class UnsubscribeHandler extends AbstractHandler {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private WxOpenIdManageService wxOpenIdManageService;

    @Autowired
    private LoginService loginService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService wxMpService,
                                    WxSessionManager sessionManager) {
        String openId = wxMessage.getFromUser();
        this.logger.info("取消关注用户 OPENID: " + openId);
        // TODO 可以更新本地数据库为取消关注状态
        SysUser user = sysUserService.getOne(new QueryWrapper<SysUser>().eq(SysUser.COL_PUBLIC_OPEN_ID, openId));
        if (user == null){
            return null;
        }
        user.setHasFocusPublicNumber(0);
        sysUserService.updateById(user);

        // 存放公众号openId以及是否关注的状态
        WxOpenIdManage wxOpenIdManage = loginService.getOpenIdManageInfoByPublicOpenId(wxMessage.getFromUser());
        wxOpenIdManage.setHasFocusPublicNumber(0);
        wxOpenIdManage.setUpdatedTime(new Date());
        wxOpenIdManageService.updateById(wxOpenIdManage);
        return null;
    }

}
